package cn.qianxun.meta.common.log.changeField.util;


import cn.qianxun.meta.common.log.changeField.annotation.ChangeLog;
import com.baomidou.mybatisplus.extension.service.IService;
import lombok.RequiredArgsConstructor;
import org.aspectj.lang.JoinPoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.io.Serializable;

/**
 * 基础解析类
 * 单表编辑时可以直接使用id来查询
 * 如果为多表复杂逻辑，请自行编写具体实现类
 *
 * @author fuzhilin
 */
@Component
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class DefaultContentParse implements ContentParser {

    private final ApplicationContext applicationContext;


    @Override
    public Object getResult(JoinPoint joinPoint, ChangeLog changeLog) {
        Object info = joinPoint.getArgs()[0];
        String idName = "id";
        if (!"id".equals(changeLog.idName())) {
            idName = changeLog.idName();
        }
        Object id = ReflectionUtils.getFieldValue(info, idName);
        Assert.notNull(id, "未解析到id值，请检查前台传递参数是否正确");
        Class idType = changeLog.idType();
        if (idType.isInstance(id)) {
            Class cls = changeLog.serviceclass();
            IService service = (IService) applicationContext.getBean(cls);
            return service.getById((Serializable) idType.cast(id));
        } else {
            throw new RuntimeException("请核实id type");
        }
    }


}
